
package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private final Config config = Config.getInstance();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public void start() {
        // TODO: [222024321072054/李欣雨]  实现 ServerSocket 的创建和监听
        try (ServerSocket serverSocket = new ServerSocket(config.getPort())) {
            System.out.println("MiniWebSvr 启动成功，监听端口：" + config.getPort());

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到新的连接：" + clientSocket.getInetAddress());
                threadPool.execute(new RequestProcessor(clientSocket));
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败或运行异常: " + e.getMessage());
            threadPool.shutdown();
        }
    }

    private static class RequestProcessor implements Runnable {
        private final Socket socket;

        public RequestProcessor(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            // TODO: [222024321072054/李欣雨]  完善请求处理流程，确保异常安全和资源关闭
            try {
                Parameter request = HttpParser.parse(socket.getInputStream());

                Router router = new Router();
                router.route(request, socket.getOutputStream());

            } catch (Exception e) {
                System.err.println("请求处理异常: " + e.getMessage());
                // TODO: [222024321072054/李欣雨] 可以在这里实现返回 500 错误页面的逻辑
                try {
                    socket.getOutputStream().write("HTTP/1.1 500 Internal Server Error\r\n\r\n".getBytes());
                } catch (IOException ignore) { }
            } finally {
                try {
                    if (socket != null) socket.close();
                } catch (IOException e) { /* ignore */ }
            }
        }
    }
}